import cv
import numpy as np
import cPickle
import math
import features
import os.path
import os
import svmutil
import random

# Active features
#a = (0,0,1)
a = (1,)
clNr = 2

# Gesture dict
train = {}
test = {}
label = {}


# SVMs
svm = None

def main():
    loadGestures()
    svmTrain()
    r = []
    for i in range(clNr):
    #for i in range(1,3):
    #for i in range(-1,2,2):
        print ''
        print label[i]
        svmR = svmClassify(test[label[i]],[i]*len(test[label[i]]))
        print svmR
        print (float(len(np.where(np.array(svmR) == label[i])[0])) / len(test[label[i]]))
        print test[label[i]]

def loadGestures():
    global train, test
    """for g in os.listdir('d2/'):
        n = g.split('.')[0]
        if len(n) == 0:
            continue
        data = cPickle.load(open('d2/'+ g))
        print n,len(data)
        x = len(data) / 10
        #train[n] = data[x:]
        #test[n] = data[:x]
        train[n] = data[5:50]
        test[n] = data[:5]"""
    for i in range(clNr):
    #for i in range(1,3):
    #for i in range(-1,2,2):
        c = 'c'+str(i)
        train[c] = []
        for j in range(200):
            train[c].append(randTup(i))
        test[c] = []
        for j in range(10):
            test[c].append(randTup(i))

def randTup(fac):
    sc = 1.0 / clNr
    return [((sc*random.random())+(sc*fac),)]
    #return [(random.random()+(fac-1),)]#random.random()+(fac-1))]
    #return [(fac*random.random(),)]#fac*random.random())]


def getFeatures(feat):
    l = [[]]*len(feat)
    for i in range(len(feat)):
        for j in range(len(a)):
            if a[j]:
                l[i].extend(list(feat[i][j]))
    return l

def svmTrain():
    global label,svm
    lc = 0.0
    #lc = -1.0
    x = []
    y = []
    for k in train:
            x.extend(getFeatures(train[k]))
            y.extend([lc]*len(train[k]))
            label[lc] = k
            lc += 1
            #lc += 2
    prob = svmutil.svm_problem(y,x)
    param = svmutil.svm_parameter('-c 1')
    svm = svmutil.svm_train(prob, param)

def svmClassify(t1,l1):
    feat = getFeatures(t1)
    lab, acc, val = svmutil.svm_predict(l1, feat, svm, '')
    return [label[i] for i in lab]

# Finds the most likely classification given the recorded known train
# KNN Classifier
def knnClassify(t1,k):
    minD = 99999
    maxKey = "None"
    candidates = []

    for key in train:
        for t2 in train[key]:
            t2Dist = features.dist(t1,t2,a)
            candidates.append((t2Dist,t2[3]))
    candidates.sort()
    candidates = candidates[:k]

    maxDict = {}
    for (_,c) in candidates:
        if not c in maxDict:
            maxDict[c] = 1
        else:
            maxDict[c] = maxDict[c] + 1

    maxKey, maxValue = '',0
    for key in maxDict:
        if maxDict[key] > maxValue:
            maxValue = maxDict[key]
            maxKey = key
            

    return maxKey

if __name__ == '__main__': main()

